﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Portal.Logic.Services;
using Portal.Logic.Services.SkillsCatalog;
using Portal.Model;
using Portal.Presentation.Models;
using Portal.Presentation.Providers;
using Portal.Presentation.Services;

namespace Portal.Presentation.Controllers
{
	[CustomHandleError(View = "Error")]
	public class DashboardController : ControllerBase
	{
		#region Fields

		private readonly IUserInfoService _userInfoService;
		private readonly ICurriculumVitaeService _curriculumVitaeService;

		#endregion Fields

		#region .ctor

		/// <summary>
		/// Initializes a new instance of the <see cref="DashboardController" /> class.
		/// </summary>
		/// <param name="security">The session.</param>
		/// <exception cref="System.ArgumentNullException">security</exception>
		public DashboardController(ISecurityProvider security, ISessionService session, IUserInfoService userInfoService, ICurriculumVitaeService curriculumVitaeService)
			: base(security, session)
		{
			if (userInfoService == null)
			{
				throw new ArgumentNullException("userInfoService");
			}
			if (curriculumVitaeService == null)
			{
				throw new ArgumentNullException("curriculumVitaeService");
			}
			_curriculumVitaeService = curriculumVitaeService;
			_userInfoService = userInfoService;
		}

		#endregion .ctor

		//
		// GET: /Dashboard/
		public ActionResult Index()
		{
			var user = SecurityProvider.GetUser(GetLogon());
			var model = new DashboardViewModel();

			CheckUserInfo(user, model);
			CheckCV(user, model);
			return View(model);
		}

		private void CheckCV(IUser user, DashboardViewModel model)
		{
			var cv = _curriculumVitaeService.GetBy(user);
			if (cv == null)
			{
				model.AddWarning("CV", "CV is not created!", "CV", "Edit");
			}
			else if (!_curriculumVitaeService.IsUpToDate(cv, DateTime.Now))
			{
				model.AddWarning("CV", "CV has not been updated since " + cv.UpdatedOn.ToShortDateString() + "!", "CV", "Preview");
			}
		}

		private void CheckUserInfo(IUser user, DashboardViewModel model)
		{
			var userInfo = _userInfoService.GetBy(user);
			if (userInfo != null && !_userInfoService.IsValid(userInfo))
			{
				model.Add(new DashboardWarning()
				{
					Header = "USER PROFILE",
					Message = "User info is not complete!",
					Controller = "UserInfo",
					Action = "Edit"
				});
			}
		}
	}
}